﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Infrastructure;
using PickingBusiness;
using Picking.Common;
using System.IO;
using Infrastructure.Util;

namespace Picking_Winform
{
    public partial class SebangoAndDNoSetupView : FormBase
    {
        private SebangoAndDNoSetupModel model = new SebangoAndDNoSetupModel();
        private LightAndDNoSetupModel modelDNo = new LightAndDNoSetupModel();
        private DataTable dtSebangoAndDNoSetup = null;
        private bool hasDeletedData = false;

        /// <summary>
        /// Constructor
        /// </summary>
        public SebangoAndDNoSetupView()
        {
            InitializeComponent();
            this.Controls.Add(base.txtTitle);
            this.comboBox1.Items.Clear();
            this.comboBox1.Items.AddRange(base.items);
            this.comboBox1.SelectedIndex = 0;
        }

        /// <summary>
        /// Get Form Width
        /// </summary>
        /// <returns></returns>
        protected override int GetFormWidth()
        {
            return 820;
        }

        /// <summary>
        /// Set Form Title
        /// </summary>
        private void SetFormTitle()
        {
            this.Text = txtTitle.Text = "背番号和图纸号的设定";
        }

        /// <summary>
        /// Form Shown
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SebangoAndDNoSetupView_Shown(object sender, EventArgs e)
        {
            this.SetFormTitle();
        }

        /// <summary>
        /// Form Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SebangoAndDNoSetupView_Load(object sender, EventArgs e)
        {
            this.InitSebangoAndDNoSetup();

            this.InitDNoSetup();

            this.hasDeletedData = false;
        }

        private string GetLineCode()
        {
            string lineCode = ConfigInfo.LineCodeA;

            if (this.comboBox1.SelectedIndex == 0)
            {
                lineCode = ConfigInfo.LineCodeA;
            }
            else if (this.comboBox1.SelectedIndex == 1)
            {
                lineCode = ConfigInfo.LineCodeB;
            }
            else if (this.comboBox1.SelectedIndex == 2)
            {
                lineCode = ConfigInfo.LineCodeC;
            }

            return lineCode;
        }

        /// <summary>
        /// Init Sebango And DNo
        /// Get Sebango And DNo Setup From Database
        /// </summary>
        private void InitSebangoAndDNoSetup()
        {
            string lineCode = this.GetLineCode();
            this.model = Configuration.GetSebangoAndDNoSetup(lineCode);
            
            this.grdMachineSet.DataSource = this.model.SebangoAndMachineSetupTable;

            this.dtSebangoAndDNoSetup = model.SebangoAndDNoSetupTable.Clone();

            this.grdMachineSet.ClearSelection();
        }

        /// <summary>
        /// Init DNo
        /// Get Light And DNo Setup From Database
        /// </summary>
        private void InitDNoSetup()
        {
            string lineCode = this.GetLineCode();
            this.modelDNo = Configuration.GetLightAndDNoSetup(lineCode);

            this.InitDNoListBox();
        }

        /// <summary>
        /// Init DNo List Box
        /// </summary>
        private void InitDNoListBox()
        {
            this.modelDNo.LightAndDNoSetupTableCopy
                = this.modelDNo.LightAndDNoSetupTable.Copy();

            this.SortDataTable(this.modelDNo.LightAndDNoSetupTableCopy, "Design_No");
            this.lstAllDNo.DataSource = this.modelDNo.LightAndDNoSetupTableCopy;
            this.lstAllDNo.DisplayMember = "Design_No";

            this.dtSebangoAndDNoSetup.Clear();
            this.lstIncludedDNo.DataSource = this.dtSebangoAndDNoSetup;
            this.lstIncludedDNo.DisplayMember = "Design_No";
        }

        /// <summary>
        /// Sort Data Table
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="columnName"></param>
        private void SortDataTable(DataTable dt,string columnName)
        {
            DataTable dtTemp = dt.Clone();

            DataRow[] drs = dt.Select("", columnName);

            foreach (DataRow row in drs)
            {
                dtTemp.ImportRow(row);
            }

            dt.Clear();

            foreach (DataRow row in dtTemp.Rows)
            {
                dt.ImportRow(row);
            }
        }

        /// <summary>
        /// Clear Sebango And Machine Name
        /// </summary>
        private void ClearSebangoAndMachineName()
        {
            this.txtSebango.Text = string.Empty;
            this.txtMachineName.Text = string.Empty;
        }

        /// <summary>
        /// Do Validation
        /// </summary>
        /// <returns></returns>
        private bool DoValidation()
        {
            List<int> lightNumbers = new List<int>();
            List<string> designNoList = new List<string>();

            if (string.IsNullOrEmpty(this.txtSebango.Text.Trim())
                && string.IsNullOrEmpty(this.txtMachineName.Text.Trim()))
            {
                if (this.hasDeletedData)
                {
                    return true;
                }
                else
                {
                    MessageBox.Show("背番号和机种名均不能为空!",
                                    "验证",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);
                    return false;
                }
            }

            int intSebango = 0;

            string sebango = this.txtSebango.Text.Trim();

            if (string.IsNullOrEmpty(sebango))
            {
                MessageBox.Show("背番号不能为空!",
                                "验证",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Warning);
                return false;
            }
            else
            {
                if (!int.TryParse(sebango, out intSebango))
                {
                    MessageBox.Show("背番号必须是个整型数值!",
                                    "验证",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);

                    return false;
                }

                if (intSebango < 0)
                {
                    MessageBox.Show("背番号不能为负数！",
                                    "验证",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);

                    return false;
                }

                if (!this.txtSebango.ReadOnly)
                {
                    foreach (DataRow row in this.model.SebangoAndMachineSetupTable.Rows)
                    {
                        if (string.Equals(this.txtSebango.Text.Trim(), row["Sebango_ID"].ToString().Trim()))
                        {
                            MessageBox.Show("背番号（" + this.txtSebango.Text.Trim() + "）不能重复!",
                                            "验证",
                                            MessageBoxButtons.OK,
                                            MessageBoxIcon.Warning);
                            return false;
                        }
                    }
                }
            }


            string machineName = this.txtMachineName.Text.Trim();

            if (string.IsNullOrEmpty(machineName))
            {

                MessageBox.Show("机种名不能为空!",
                                "验证",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Warning);
                return false;
            }
            else
            {
                foreach (DataRow row in this.model.SebangoAndMachineSetupTable.Rows)
                {
                    if (string.Equals(this.txtMachineName.Text.Trim(), row["Machine_Name"].ToString().Trim()))
                    {
                        if (!string.Equals(this.txtSebango.Text.Trim(), row["Sebango_ID"].ToString().Trim()))
                        {
                            MessageBox.Show("机种名（" + this.txtMachineName.Text.Trim() + "）不能重复!",
                                            "验证",
                                            MessageBoxButtons.OK,
                                            MessageBoxIcon.Warning);
                            return false;
                        }
                    }
                }
            }

            return true;
        }

        /// <summary>
        /// Save Event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            this.btnSave.Focus();

            if (!this.DoValidation())
            {
                return;
            }

            if (!this.txtSebango.ReadOnly)
            {
                if (!string.IsNullOrEmpty(this.txtSebango.Text.Trim())
                    && !string.IsNullOrEmpty(this.txtMachineName.Text.Trim()))
                {
                    DataRow newRow = this.model.SebangoAndMachineSetupTable.NewRow();

                    newRow["Sebango_ID"] = this.txtSebango.Text.Trim();
                    newRow["Machine_Name"] = this.txtMachineName.Text.Trim();
                    this.model.SebangoAndMachineSetupTable.Rows.Add(newRow);

                    this.model.SebangoAndDNoSetupTable.Merge(this.dtSebangoAndDNoSetup);
                }
            }
            else
            {
                foreach (DataRow row in this.model.SebangoAndMachineSetupTable.Rows)
                {
                    if (string.Equals(this.txtSebango.Text.Trim(), row["Sebango_ID"].ToString().Trim()))
                    {
                        row["Machine_Name"] = this.txtMachineName.Text.Trim();
                    }
                }

                for (int i = this.model.SebangoAndDNoSetupTable.Rows.Count - 1; i >= 0; i--)
                {
                    string subSebango
                        = this.model.SebangoAndDNoSetupTable.Rows[i]["Sebango_ID"].ToString().Trim();

                    if (string.Equals(subSebango, this.txtSebango.Text.Trim()))
                    {
                        this.model.SebangoAndDNoSetupTable.Rows.RemoveAt(i);
                    }
                }

                this.model.SebangoAndDNoSetupTable.Merge(this.dtSebangoAndDNoSetup);
            }

            string lineCode = this.GetLineCode();
            bool result = Configuration.SaveSebangoAndDNoSetup(this.model, lineCode);

            if (result)
            {
                this.InitDNoListBox();
                this.ClearSebangoAndMachineName();
                this.txtSebango.ReadOnly = false;
                this.txtSebango.BackColor = Color.White;

                MessageBox.Show("保存成功!", "保存", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.hasDeletedData = false;
            }
            else
            {
                MessageBox.Show("保存失败!", "保存", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// Cancel Event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.btnCancel.Focus();

            this.InitSebangoAndDNoSetup();
            this.InitDNoListBox();
            this.ClearSebangoAndMachineName();
            this.txtSebango.ReadOnly = false;
            this.txtSebango.BackColor = Color.White;
            this.hasDeletedData = false;
        }

        /// <summary>
        /// Return Event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReturn_Click(object sender, EventArgs e)
        {
            this.CloseCurrentWindow();
        }

        /// <summary>
        /// Include DNo
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInclude_Click(object sender, EventArgs e)
        {
            this.btnInclude.Focus();

            List<int> selectedIndexes = new List<int>();

            for (int i = 0; i < this.lstAllDNo.Items.Count; i++)
            {
                if (this.lstAllDNo.SelectedItems.Contains(this.lstAllDNo.Items[i]))
                {
                    selectedIndexes.Add(i);
                }
            }

            foreach (int index in selectedIndexes)
            {
                DataRow newRow = this.dtSebangoAndDNoSetup.NewRow();

                newRow["Sebango_ID"] = this.txtSebango.Text.Trim();
                newRow["Design_No"]
                    = this.modelDNo.LightAndDNoSetupTableCopy.Rows[index]["Design_No"];
                this.dtSebangoAndDNoSetup.Rows.Add(newRow);
            }

            this.SortDataTable(this.dtSebangoAndDNoSetup, "Design_No");

            for (int i = selectedIndexes.Count - 1; i >= 0; i--)
            {
                this.modelDNo.LightAndDNoSetupTableCopy.Rows.RemoveAt(selectedIndexes[i]);
            }
        }

        /// <summary>
        /// Exclude DNo
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExclude_Click(object sender, EventArgs e)
        {
            this.btnExclude.Focus();

            List<int> selectedIndexes = new List<int>();

            for (int i = 0; i < this.lstIncludedDNo.Items.Count; i++)
            {
                if (this.lstIncludedDNo.SelectedItems.Contains(this.lstIncludedDNo.Items[i]))
                {
                    selectedIndexes.Add(i);
                }
            }

            foreach (int index in selectedIndexes)
            {
                DataRow newRow = this.modelDNo.LightAndDNoSetupTableCopy.NewRow();

                newRow["Design_No"] = this.dtSebangoAndDNoSetup.Rows[index]["Design_No"];
                this.modelDNo.LightAndDNoSetupTableCopy.Rows.Add(newRow);
            }

            this.SortDataTable(this.modelDNo.LightAndDNoSetupTableCopy, "Design_No");

            for (int i = selectedIndexes.Count - 1; i >= 0; i--)
            {
                this.dtSebangoAndDNoSetup.Rows.RemoveAt(selectedIndexes[i]);
            }
        }

        /// <summary>
        /// Cell Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grdMachineSet_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex < 0)
            {
                return;
            }

            if (e.RowIndex < 0)
            {
                return;
            }

            if ((this.grdMachineSet.NewRowIndex < 0)
                || (e.RowIndex < this.grdMachineSet.NewRowIndex))
            {
                string sebango
                    = this.model.SebangoAndMachineSetupTable.Rows[e.RowIndex]["Sebango_ID"].ToString().Trim();

                string machineName
                    = this.model.SebangoAndMachineSetupTable.Rows[e.RowIndex]["Machine_Name"].ToString().Trim();

                if (string.Equals(this.grdMachineSet.Columns[e.ColumnIndex].Name, "colDelete"))
                {
                    this.grdMachineSet.Rows.RemoveAt(e.RowIndex);
                    this.grdMachineSet.Update();
                    this.grdMachineSet.EndEdit();
                    this.hasDeletedData = true;

                    for (int i = this.model.SebangoAndDNoSetupTable.Rows.Count - 1; i >= 0; i--)
                    {
                        string subSebango
                            = this.model.SebangoAndDNoSetupTable.Rows[i]["Sebango_ID"].ToString().Trim();

                        if (string.Equals(subSebango, sebango))
                        {
                            this.model.SebangoAndDNoSetupTable.Rows.RemoveAt(i);

                            if (this.txtSebango.ReadOnly)
                            {
                                this.InitDNoListBox();
                                this.ClearSebangoAndMachineName();
                                this.txtSebango.ReadOnly = false;
                                this.txtSebango.BackColor = Color.White;
                            }
                        }
                    }
                }
                else
                {
                    this.txtSebango.Text = sebango;
                    this.txtMachineName.Text = machineName;

                    this.txtSebango.ReadOnly = true;
                    this.txtSebango.BackColor = Color.LightGray;

                    this.dtSebangoAndDNoSetup.Clear();
                    this.modelDNo.LightAndDNoSetupTableCopy
                         = this.modelDNo.LightAndDNoSetupTable.Copy();

                    for (int i = 0; i < this.model.SebangoAndDNoSetupTable.Rows.Count; i++)
                    {
                        string subSebango
                            = this.model.SebangoAndDNoSetupTable.Rows[i]["Sebango_ID"].ToString().Trim();

                        if (string.Equals(subSebango, sebango))
                        {
                            this.dtSebangoAndDNoSetup.ImportRow(this.model.SebangoAndDNoSetupTable.Rows[i]);

                            string subDNo
                                = this.model.SebangoAndDNoSetupTable.Rows[i]["Design_No"].ToString().Trim();

                            for (int j = this.modelDNo.LightAndDNoSetupTableCopy.Rows.Count - 1; j >= 0; j--)
                            {
                                string lightDNo
                                    = this.modelDNo.LightAndDNoSetupTableCopy.Rows[j]["Design_No"].ToString().Trim();

                                if (string.Equals(subDNo, lightDNo))
                                {
                                    this.modelDNo.LightAndDNoSetupTableCopy.Rows.RemoveAt(j);
                                }
                            }
                        }
                    }

                    this.SortDataTable(this.dtSebangoAndDNoSetup, "Design_No");
                    this.SortDataTable(this.modelDNo.LightAndDNoSetupTableCopy, "Design_No");
                    this.lstAllDNo.DataSource = this.modelDNo.LightAndDNoSetupTableCopy;
                }
            }
        }

        /// <summary>
        /// Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLoad_Click(object sender, EventArgs e)
        {
            bool validated = false;

            string currentTime = int.Parse(DateTime.Now.ToString("HHmm")).ToString("0000");

            if (this.txtPassword.Text.Trim().Length == 4)
            {
                string password = string.Empty;
                password += this.txtPassword.Text.Trim().Substring(3, 1);
                password += this.txtPassword.Text.Trim().Substring(2, 1);
                password += this.txtPassword.Text.Trim().Substring(1, 1);
                password += this.txtPassword.Text.Trim().Substring(0, 1);

                if (string.Equals(currentTime, password))
                {
                    validated = true;
                }
            }

            if (!validated)
            {
                MessageBox.Show("密码不正确!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            Stream myStream;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.InitialDirectory = "c:\\";
            openFileDialog1.Filter = "txt files (*.csv)|*.csv";
            openFileDialog1.FilterIndex = 1;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if ((myStream = openFileDialog1.OpenFile()) != null)
                {
                    if (myStream == null)
                    {
                        return;
                    }
                }
                else
                {
                    return;
                }
            }
            else
            {
                return;
            }

            //create object of CSVReader and pass the stream
            CSVReader reader = new CSVReader(myStream);

            string[] data = new string[100];
            
            while ((data = reader.GetCSVLine()) != null)
            {
                if (data.Length >= 2)
                {
                    string sebango = data[0].ToString().Trim();

                    this.RemoveSebangoAndDNo(sebango);

                    DataRow newRow = this.model.SebangoAndMachineSetupTable.NewRow();

                    newRow["Sebango_ID"] = sebango;
                    newRow["Machine_Name"] = data[1].Trim();
                    this.model.SebangoAndMachineSetupTable.Rows.Add(newRow);

                    for (int i = 2; i < data.Length; i++)
                    {
                        int temp = 0;

                        if (!int.TryParse((data[i]).Trim(), out temp))
                        {
                            break;
                        }

                        string lightNo = int.Parse(data[i].Trim()).ToString();
                        string DNo = this.GetDNoByLightNo(lightNo);

                        if (!string.IsNullOrEmpty(DNo.Trim()))
                        {
                            DataRow newRowDNo = this.model.SebangoAndDNoSetupTable.NewRow();

                            newRowDNo["Sebango_ID"] = data[0].Trim();
                            newRowDNo["Design_No"] = DNo;
                            this.model.SebangoAndDNoSetupTable.Rows.Add(newRowDNo);
                        }
                    }
                }
            }

            string lineCode = this.GetLineCode();
            bool result = Configuration.SaveSebangoAndDNoSetup(this.model, lineCode);

            if (result)
            {
                this.InitSebangoAndDNoSetup();
                this.InitDNoListBox();
                this.ClearSebangoAndMachineName();
                this.txtSebango.ReadOnly = false;
                this.txtSebango.BackColor = Color.White;
                this.hasDeletedData = false;

                MessageBox.Show("保存成功!", "保存", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.hasDeletedData = false;
            }
            else
            {
                MessageBox.Show("保存失败!", "保存", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            if (myStream != null)
            {
                myStream.Close();
            }
        }

        /// <summary>
        /// Get DNo By Light No
        /// </summary>
        /// <param name="lightNo"></param>
        /// <returns></returns>
        private string GetDNoByLightNo(string lightNo)
        {
            string DNo = string.Empty;

            foreach (DataRow row in this.modelDNo.LightAndDNoSetupTable.Rows)
            {
                if (string.Equals(lightNo, row["Light_No"].ToString().Trim()))
                {
                    DNo = row["Design_No"].ToString().Trim();
                    break;
                }
            }

            return DNo;
        }

        /// <summary>
        /// Remove Sebango And DNo
        /// </summary>
        /// <param name="sebango"></param>
        private void RemoveSebangoAndDNo(string sebango)
        {
            for (int i = this.model.SebangoAndMachineSetupTable.Rows.Count - 1; i >= 0; i--)
            {
                if (string.Equals(sebango, this.model.SebangoAndMachineSetupTable.Rows[i]["Sebango_ID"].ToString().Trim()))
                {
                    this.model.SebangoAndMachineSetupTable.Rows.RemoveAt(i);
                }
            }

            for (int i = this.model.SebangoAndDNoSetupTable.Rows.Count - 1; i >= 0; i--)
            {
                if (string.Equals(sebango, this.model.SebangoAndDNoSetupTable.Rows[i]["Sebango_ID"].ToString().Trim()))
                {
                    this.model.SebangoAndDNoSetupTable.Rows.RemoveAt(i);
                }
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.InitSebangoAndDNoSetup();
            this.InitDNoSetup();
            this.ClearSebangoAndMachineName();
            this.txtSebango.ReadOnly = false;
            this.txtSebango.BackColor = Color.White;
            this.hasDeletedData = false;
        }
    }
}